package me.keiwu.user.service.impl;

import com.alibaba.fastjson.JSON;
import me.keiwu.pub.data.service.MiscKey;
import me.keiwu.pub.data.service.UserMiscBean;
import me.keiwu.pub.util.CacheUtil;
import me.keiwu.user.dao.UserMiscDao;
import me.keiwu.user.domain.UserMisc;
import me.keiwu.user.service.UserMiscService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kei on 08/12/2017.
 */
@Service
@Transactional
public class UserMiscServiceImpl implements UserMiscService {


    @Autowired
    private UserMiscDao userMiscDao;
    @Autowired
    private CacheUtil cacheUtil;

    @Override
    public void save(Long userId, MiscKey key, String value) {
        List<UserMiscBean> cacheMisc = cacheUtil.getUserMisc(userId);
        UserMisc dbMisc = new UserMisc();
        if (cacheMisc == null) {
            // 缓存没有
            dbMisc = userMiscDao.findOne(userId);
            if (dbMisc != null && StringUtils.isNotBlank(dbMisc.getMisc())) {
                cacheMisc  = JSON.parseArray(dbMisc.getMisc(), UserMiscBean.class);
            } else {
                dbMisc = new UserMisc();
                cacheMisc = new ArrayList<>();
            }
        }

        boolean found = false;
        for (UserMiscBean miscBean : cacheMisc) {
            if (miscBean.getKey() == key.getId()) {
                miscBean.setValue(value);
                found = true;
                break;
            }
        }
        if (!found) {
            UserMiscBean bean = new UserMiscBean();
            bean.setKey(key.getId());
            bean.setValue(value);
            cacheMisc.add(bean);
        }
        // 加入缓存
        cacheUtil.setUserMisc(userId, dbMisc.getMisc());

        // 设置数据库对象
        dbMisc.setUserId(userId);
        dbMisc.setMisc(JSON.toJSONString(cacheMisc));
        userMiscDao.save(dbMisc);
    }

    @Override
    public UserMiscBean get(Long userId, MiscKey key) {
        List<UserMiscBean> cacheMisc = cacheUtil.getUserMisc(userId);
        if (cacheMisc == null) {
            // 缓存没有
            UserMisc misc = userMiscDao.findOne(userId);
            if (misc == null || StringUtils.isBlank(misc.getMisc())) return null;
            // 转换成bean list，加入缓存
            cacheMisc = JSON.parseArray(misc.getMisc(), UserMiscBean.class);
            cacheUtil.setUserMisc(userId, misc.getMisc());
        }
        for (UserMiscBean miscBean : cacheMisc) {
            if (miscBean.getKey() == key.getId()) return miscBean;
        }
        return null;
    }


}
